import PyInstaller.__main__
import os
import shutil
from global_settings import debug_print, APP_VERSION, APP_NAME


# 清理之前的构建文件
def clean_previous_builds():
    build_dirs = ['build', 'dist']
    spec_files = [f for f in os.listdir('.') if f.endswith('.spec')]

    for dir_name in build_dirs:
        if os.path.exists(dir_name):
            try:
                shutil.rmtree(dir_name)
                debug_print(f"已删除目录: {dir_name}")
            except Exception as e:
                debug_print(f"删除目录 {dir_name} 时出错: {e}")
        else:
            debug_print(f"目录不存在，无需删除: {dir_name}")

    for spec_file in spec_files:
        try:
            os.remove(spec_file)
            debug_print(f"已删除文件: {spec_file}")
        except Exception as e:
            debug_print(f"删除文件 {spec_file} 时出错: {e}")


# 打包配置
app_name = f"{APP_NAME}_v{APP_VERSION}"
main_script = "main.py"
icon_path = "favicon.ico"

# 检查关键文件是否存在
required_files = [main_script, icon_path, "config.json", "global_settings.py"]
for file in required_files:
    if not os.path.exists(file):
        raise FileNotFoundError(f"必要文件未找到: {file}")

# 检查protocol_configs目录
protocol_configs_dir = "protocol_configs"
if not os.path.exists(protocol_configs_dir):
    raise FileNotFoundError(f"协议配置目录未找到: {protocol_configs_dir}")

# 验证protocol_configs目录下有JSON文件
json_files = [f for f in os.listdir(protocol_configs_dir) if f.endswith('.json')]
if not json_files:
    raise FileNotFoundError(f"在 {protocol_configs_dir} 目录中未找到任何JSON文件")

debug_print(f"找到协议配置文件: {json_files}")

# 清理之前的构建
clean_previous_builds()

# 构建PyInstaller参数
params = [
    main_script,
    '--name', app_name,
    '--windowed',  # 无控制台窗口
    '--onefile',  # 打包成单个exe
    '--clean',  # 清理临时文件
    '--noconfirm',  # 不询问覆盖
    # 添加数据文件
    '--add-data', f'config.json{os.pathsep}.',
    '--add-data', f'global_settings.py{os.pathsep}.',
    '--add-data', f'{protocol_configs_dir}{os.pathsep}protocol_configs',  # 添加整个protocol_configs目录
    '--add-data', f'{icon_path}{os.pathsep}.',
    '--icon', icon_path
]

# 添加所有必需的Python文件作为隐藏导入
required_py_modules = [
    'liquid_cooler_ui',
    'serial_manager',
    'protocol_parser',
    'data_logger',
    'config_manager',
    'serial_worker',
    'data_logger',
    'global_setting'
]

for module in required_py_modules:
    params.extend(['--hidden-import', module])

# 执行打包
debug_print("开始打包...")
try:
    PyInstaller.__main__.run(params)
    debug_print("打包完成！")

    # 显示打包结果
    dist_dir = "dist"
    if os.path.exists(dist_dir):
        exe_files = [f for f in os.listdir(dist_dir) if f.endswith('.exe')]
        if exe_files:
            exe_path = os.path.join(dist_dir, exe_files[0])
            exe_size = os.path.getsize(exe_path) / (1024 * 1024)  # MB
            debug_print(f"生成的EXE文件: {exe_path}")
            debug_print(f"文件大小: {exe_size:.2f} MB")

except Exception as e:
    debug_print(f"打包过程中出现错误: {e}")
    raise